/**
 * 
 */
package com.warriormill.warriorengine;

import java.util.concurrent.TimeUnit;

import com.warriormill.warriorengine.drawable.SpriteTile;

import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.util.Log;
//import android.view.SurfaceHolder;
//import android.view.SurfaceView;
import android.view.MotionEvent;
import android.view.View;

/**
 * @author maximo guerrero
 *
 */
public class GameEngineView extends View {
	SpriteTile st;
	
	
	GameLoop gameloop;
	private class GameLoop extends Thread
	{
		private volatile boolean running=true;
		public void run()
		{
			while(running)
			{
				try{
					TimeUnit.MILLISECONDS.sleep(1);
					postInvalidate();
					pause();
					
				}
				catch(InterruptedException ex)
				{
					running=false;
				}
				
			}
			
		}
		public void pause()
		{
			running=false;
		}
		public void start()
		{
			running=true;
			run();
		}
		public void safeStop()
		{
			running=false;
			interrupt();
		}

		
		
	}
	public void unload()
	{
		gameloop.safeStop();
		
	}
	
	public GameEngineView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		init(context);
		
	}
	public GameEngineView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		init(context);
	}
	public GameEngineView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		init(context);
	}
	
	private void init(Context context)
	{
		st = new SpriteTile(R.drawable.buster, R.xml.buster, context);
		gameloop = new GameLoop();
		gameloop.run();
		
	}
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		// TODO Auto-generated method stub
		//super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		System.out.println("Width " + widthMeasureSpec);
		setMeasuredDimension(100, 100);
	}
	

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		//super.onDraw(canvas);
		st.setXpos(15);
		st.setYpos(15);
	
		st.draw(canvas);
		gameloop.start();
		
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		//return super.onTouchEvent(event);
		Log.e("Linhnv","event.getX() = " + event.getX());
		
		return true;
	}
	

}
